package patrol.mobile.com.mobilepatrol.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.realm.Realm;
import io.realm.RealmAsyncTask;
import patrol.mobile.com.mobilepatrol.DBHelper;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.route_query.RouteManagePer;
import patrol.mobile.com.mobilepatrol.adapter.InitAdapter;
import patrol.mobile.com.mobilepatrol.api.DataUtil;
import patrol.mobile.com.mobilepatrol.api.MyHandler;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.Handong;
import patrol.mobile.com.mobilepatrol.bean.Hddqjcb;
import patrol.mobile.com.mobilepatrol.bean.InitDownLoadInfoBean;
import patrol.mobile.com.mobilepatrol.bean.Org;
import patrol.mobile.com.mobilepatrol.bean.Qiaoliang;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjjcb;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjqsb;
import patrol.mobile.com.mobilepatrol.bean.QldqjcBjqstpb;
import patrol.mobile.com.mobilepatrol.bean.Qldqjcb;
import patrol.mobile.com.mobilepatrol.manager.HManager;
import patrol.mobile.com.mobilepatrol.manager.OrgManager;
import patrol.mobile.com.mobilepatrol.manager.QManager;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.persenter.CarPer;
import patrol.mobile.com.mobilepatrol.persenter.OrgPer;
import patrol.mobile.com.mobilepatrol.persenter.QHMesPer;
import patrol.mobile.com.mobilepatrol.persenter.RoutePer;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.view.CarView;
import patrol.mobile.com.mobilepatrol.view.CompanyView;
import patrol.mobile.com.mobilepatrol.view.QHMesView;
import patrol.mobile.com.mobilepatrol.view.RouteManageView;
import patrol.mobile.com.mobilepatrol.view.RouteView;
import patrol.mobile.com.mobilepatrol.widget.dialog.EditDialog;

/**
 * Created by apple on 17/9/28.
 */

public class InitActivity extends BaseActivity implements QHMesView ,CompanyView,CarView,RouteView,RouteManageView{
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    private BaseQuickAdapter mAdapter;
    private ArrayList<String> mList;
    private RealmAsyncTask transaction;
    private AlertDialog.Builder builder;
    private ProgressDialog progressDialog;
    private List<Org> orgs ;
    private String mOrgNo;
    private DBHelper dbHelper;
    private PatrolApp ac;
    String type ="";
    private MyHandler handler;
    private String toastAll = "";
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_init;
    }

    @Override
    public void initView() {
        //super的重要性
        super.initView();

        dbHelper=new DBHelper(this);
        ac= (PatrolApp) getApplication();


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        initDialog();
    }

    private void initDialog() {
        builder=new AlertDialog.Builder(this);
        builder.setTitle("请选择要初始化数据的分局");

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("初始化数据中,请稍候...");
        progressDialog.setTitle("提示");
        progressDialog.setCancelable(true);
    }

    @Override
    public void initData() {
        mList = new ArrayList<>();
        Resources res = getResources();
        String[] init = res.getStringArray(R.array.init);
        for (int i = 0; i < init.length; i++) {
            mList.add(init[i]);
        }
        mAdapter = new InitAdapter(this, mList);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void setListener() {
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (position) {
                    case 0:
                        progressDialog.setMessage("初始化数据中,请稍候...");
                        progressDialog.show();
                        OrgPer cp1 = new OrgPer(InitActivity.this,"org");
                        cp1.getCompays();
                        break;
//                    case 1:
//                        isAll = false;
//                        showLoading();
//                        UserPer userPer = new UserPer(InitActivity.this);
//                        userPer.getUsers();
//                        break;

                    case 1:
                        final EditDialog dialog = new EditDialog(InitActivity.this, R.style.Dialog);
                        dialog.show();
                        dialog.setmListener(new EditDialog.SureListener() {
                            @Override
                            public void onSure(String rc, String sp, String ep) {
                                showLoading();
                                dialog.dismiss();
                                Map<String, String> map = new HashMap<>();
                                map.put("userName", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).username);
                                map.put("passWord", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).pw);
                                if (rc != null && !rc.equals("")) {
                                    map.put("roadcode", rc);
                                }
                                if (sp != null && !sp.equals("")) {
                                    map.put("spos", "K" + sp);
                                }
                                if (ep != null && !ep.equals("")) {
                                    map.put("epos", "K" + ep);
                                }
                                QHMesPer qhMesPer = new QHMesPer(InitActivity.this, map);
                                qhMesPer.getQHMes(Urls.queryQhxx);
                            }
                        });
                        break;
//                    case 3:
//                        isAll = false;
//                        showLoading();
//                        OrgPer cp = new OrgPer(InitActivity.this,"org");
//                        cp.getCompays();
//                        break;
//                    case 4:
//                        isAll = false;
//                        showLoading();
//                        RoutePer rp = new RoutePer(InitActivity.this,"route");
//                        rp.getRoutes();
//                        break;
//                    case 5:
//                        isAll = false;
//                        showLoading();
//                        CarPer carp = new CarPer(InitActivity.this,"cars");
//                        carp.getCars();
//                        break;
                    case 3:
                        type = "";
                        switch (UserManager.getUser().orgtype){

                            case "总局":
                                orgs = OrgManager.get();
                                if(orgs.size()==0) {
                                    OrgPer op = new OrgPer(InitActivity.this,"org");
                                    op.getCompays();
                                }else{
                                    builder.setAdapter(getArrayAdapter(orgs), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            Org org = orgs.get(i);
                                            mOrgNo = org.org_No;
                                        loadOrgStructData2(mOrgNo);
                                        }
                                    });
                                    AlertDialog dialog2= builder.create();
                                    dialog2.setCanceledOnTouchOutside(false);
                                    dialog2.show();
                                }
                                break;
                            case "分局":
                                mOrgNo = UserManager.getOrgNo();
                                loadOrgStructData2(mOrgNo);
                                break;
                        }

                        break;
                    case 2:
                        showLoading();
//                        progressDialog.setMessage("初始化数据中,请稍候...");
//                        progressDialog.show();
                        type = "task";
                        DataUtil.initData(ac, handler, type);
                        break;
//                    case 8:
//                        isAll = false;
//                        showLoading();
//                        RouteManagePer rmPer = new RouteManagePer(InitActivity.this);
//                        rmPer.getRoutes();
//                        break;
                }
            }
        });
        handler=new MyHandler(InitActivity.this){
            @Override
            public void onResultSuccess(Object data) {
                Gson gson=new Gson();
                final InitDownLoadInfoBean initData=gson.fromJson(gson.toJson(data),InitDownLoadInfoBean.class);

                new Thread(){
                    @Override
                    public void run() {
                        synchronized (dbHelper) {
                            dbHelper.insertInitData(initData);
                            dateLoadCompleteHandler.sendEmptyMessage(0);
                        }
                    }
                }.start();
            }

            @Override
            public void onResultFailure() {
                if(progressDialog.isShowing()&&!isFinishing())
                    progressDialog.dismiss();
            }
        };
    }

    private Handler dateLoadCompleteHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(progressDialog.isShowing()&&!isFinishing())
                progressDialog.dismiss();
            hideLoading();
//            if (isAll){
//                toastAll += "初始化路况调查任务成功!\n";
//                showToast(toastAll);
//                toastAll = "";
//            }else{
                if (type.equals("task") ){
                    showToast("初始化路况调查任务成功！");
                }else{
                    showToast("初始化调查数据成功！");
                }
//            }


        }
    };
    private void loadOrgStructData2(final String orgNo){
        MyHandler handler=new MyHandler(InitActivity.this){
            @Override
            public void onResultSuccess(Object data) {
                final List<LinkedTreeMap> taskData= (List<LinkedTreeMap>) data;
                new Thread(){
                    @Override
                    public void run() {
                        synchronized (dbHelper) {
                            dbHelper.deleteOrgData(orgNo);
                            dbHelper.insertTaskDataInfo(taskData);
                            dateLoadCompleteHandler.sendEmptyMessage(0);
                        }
                    }
                }.start();
            }

            @Override
            public void onResultFailure() {
                if(progressDialog.isShowing()&&!isFinishing())
                    progressDialog.dismiss();
            }
        };
        progressDialog.setMessage("初始化数据中!时间比较长，请耐心等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        DataUtil.initStructData(ac,handler,orgNo);
    }

    @Override
    public void onQHError(String e) {
        showToast(e);
    }

    @Override
    public void onRouteError(String s) {
        showToast(s);

    }

    @Override
    public void onRouteSuccess(String s) {

            toastAll +=s+"\n";
            CarPer carp1 = new CarPer(InitActivity.this,"cars");
            carp1.getCars();

    }

    @Override
    public void onCarError(String s) {
        showToast(s);

    }

    @Override
    public void onCarSuccess(String s) {

            toastAll+=s+"\n";
            RouteManagePer rmPer1 = new RouteManagePer(InitActivity.this);
            rmPer1.getRoutes();

    }

    @Override
    public void onCompanyError(String s) {
        showToast(s);
    }

    @Override
    public void onCompanySuccess(List<Org> coms) {
            toastAll += "初始化单位成功\n";
            RoutePer rp1 = new RoutePer(InitActivity.this,"route");
            rp1.getRoutes();


    }

    @Override
    public void onQHSuccess(final String s) {

        try {
            JSONObject object = new JSONObject(s);
            if (object.getInt("state") == 200) {
                QManager.clearQList2();
                HManager.clearHList();
                JSONObject result = object.getJSONObject("result");
                final JSONArray qls = result.getJSONArray("ql");
                final JSONArray hds = result.getJSONArray("hd");
                transaction = PatrolApp.realm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.createAllFromJson(Qiaoliang.class, qls.toString());
                        realm.createAllFromJson(Handong.class, hds.toString());
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
//                        //1桥梁列表
                        List<Qiaoliang> qls = QManager.getAllList();
                        if (qls != null && qls.size() > 0) {
                            for (int i=0;i<qls.size();i++){
                                //桥梁
                                Qiaoliang ql = qls.get(i);
                                if (ql.dqjc!=null&&ql.dqjc.size()>0){
                                    //循环遍历定期对象
                                    for (int dq = 0;dq<ql.dqjc.size();dq++){
                                        //定期对象
                                        Qldqjcb dqobj = ql.dqjc.get(dq);
                                        QManager.setBridegDQListUpState(dqobj.qlcode,true);

                                        List<QldqjcBjqsb> qs = dqobj.bjqs;
                                        if (qs!=null&&qs.size()>0){
                                            for (int j=0;j<qs.size();j++){
                                                QManager.setQldqjcBjqsbListUpState(qs.get(j).qldqjcid,true);
                                            }
                                        }


                                        List<QldqjcBjjcb> jc = dqobj.bjjc;
                                        if (jc!=null&&jc.size()>0){
                                            for (int j=0;j<jc.size();j++){
                                                QManager.setQldqjcBjjcbUpState(jc.get(j).qldqjcid,true);
                                            }
                                        }

                                        List<QldqjcBjqstpb> tp = dqobj.bjqstp;
                                        if (tp!=null&&tp.size()>0){
                                            for (int j=0;j<tp.size();j++){
                                                QManager.setQldqjcBjqstpbUpState(tp.get(j).qldqjcid,true);
                                            }
                                        }

                                    }
                                }
                                if (ql.jcxjc!=null&&ql.jcxjc.size()>0){
                                    for (int jc = 0;jc<ql.jcxjc.size();jc++){
                                        QManager.setBridegJCListUpState(ql.jcxjc.get(jc).qlcode,true);
                                    }
                                }
                                if ((ql.dqjc!=null&&ql.dqjc.size()>0)||(ql.jcxjc!=null&&ql.jcxjc.size()>0)){
                                    QManager.setQLUpState(ql.qlcode,true);
                                }
                            }

                        }
                        //2 涵洞列表
                        List<Handong> hds = HManager.getHList();
                        if (hds != null && hds.size() > 0) {
                            for (int i=0;i<hds.size();i++){
                                //涵洞对象
                                Handong hd = hds.get(i);
                                //定期列表
                                if (hd.dqjc!=null&&hd.dqjc.size()>0){
                                    for (int dq = 0;dq<hd.dqjc.size();dq++){
                                        Hddqjcb hddq = hd.dqjc.get(dq);
                                        HManager.setHDDQListUpState(hddq.hdcode,true);
                                    }
                                }
                                if (hd.jcxjc!=null&&hd.jcxjc.size()>0){
                                    for (int jc = 0;jc<hd.jcxjc.size();jc++){
                                        HManager.setHDJCListUpState(hd.jcxjc.get(jc).hdcode,true);
                                    }
                                }
                                if ((hd.dqjc!=null&&hd.dqjc.size()>0)||(hd.jcxjc!=null&&hd.jcxjc.size()>0)){
                                    HManager.setHDUpState(hd.hdcode,true);
                                }
                            }

                        }
                        hideLoading();
                        showToast("初始化桥梁涵洞数据成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        hideLoading();
                        showToast("数据库数据存储失败，请重新下载！");
                    }
                });
            } else {
                hideLoading();
                showToast("服务器请求错误，下载失败，请重新下载！");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (transaction != null && !transaction.isCancelled()) {
            transaction.cancel();
        }
    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(InitActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("数据下载");
    }

    @Override
    public void onRouteManageError(String s) {
        showToast(s);
    }

    @Override
    public void onRouteManageSuccess(String s) {
        if(progressDialog.isShowing()&&!isFinishing())
            progressDialog.dismiss();
        toastAll += "初始化路线查询单位信息成功!\n";
                showToast(toastAll);
                toastAll = "";


    }
}
